package luke.ui.dialogs;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.Properties;

import com.google.gson.Gson;
import luke.core.config.AppDataManager;
import luke.core.config.VersionInfo;
// 导入日志工具类
import luke.core.logging.LogUtil;
import luke.core.utils.LanguageManager; // 新增：导入LanguageManager

/**
 * 更新检查类，用于检查应用程序是否有新版本
 */
public class UpdateChecker {
    // 版本文件的URL
    private static final String VERSION_URL = "https://d.kstore.dev/download/4284/run_bpm_version.json";
    
    // 当前应用程序版本（从属性文件中读取）
    private static final String CURRENT_VERSION = getCurrentVersion();
    
    private JFrame parentFrame;
    private AppDataManager appDataManager;
    private LanguageManager languageManager; // 新增：语言管理器
    private boolean isManualCheck = false; // 是否为手动检查更新

    /**
     * 从属性文件中获取当前版本号
     * @return 当前版本号
     */
    public static String getCurrentVersion() {
        try {
            Properties props = new Properties();
            InputStream is = UpdateChecker.class.getClassLoader().getResourceAsStream("version.properties");
            if (is != null) {
                props.load(is);
                String version = props.getProperty("app.version");
                if (version != null && !version.trim().isEmpty()) {
                    return version.trim();
                }
            }
        } catch (IOException e) {
            LogUtil.error("UpdateChecker", "getCurrentVersion", "读取版本属性文件失败: " + e.getMessage());
            e.printStackTrace();
        }
        // 如果无法从属性文件获取版本号，返回默认值
        return "1.0.0-alpha.1";
    }

    
    public UpdateChecker(JFrame parentFrame, boolean isManualCheck) {
        this.parentFrame = parentFrame;
        this.appDataManager = AppDataManager.getInstance();
        this.languageManager = LanguageManager.getInstance(); // 初始化语言管理器
        this.isManualCheck = isManualCheck;
    }
    
    /**
     * 检查更新
     */
    public void checkForUpdates() {
        LogUtil.info("UpdateChecker", "checkForUpdates", "开始检查更新...");
        
        // 检查本地是否已保存版本信息，并判断当前版本是否在强制更新列表中
        checkLocalMandatoryUpdate();
        
        // 如果不是手动检查，检查是否在限制时间内
        if (!isManualCheck) {
            long lastCheckTime = appDataManager.getLastUpdateCheckTime();
            long currentTime = System.currentTimeMillis();
            long oneDayInMillis = 8 * 60 * 60 * 1000; // 8小时的毫秒数
            
            LogUtil.debug("UpdateChecker", "checkForUpdates", "上次检查时间: " + lastCheckTime + ", 当前时间: " + currentTime);
            LogUtil.debug("UpdateChecker", "checkForUpdates", "距离上次检查毫秒数: " + (currentTime - lastCheckTime));
            LogUtil.debug("UpdateChecker", "checkForUpdates", "8小时毫秒数: " + oneDayInMillis);
            
            // 如果距离上次检查时间不足8小时，跳过检查
            if (currentTime - lastCheckTime < oneDayInMillis) {
                LogUtil.info("UpdateChecker", "checkForUpdates", "距离上次检查更新不足8小时，跳过检查");
                return;
            }
            
            // 更新上次检查时间
            LogUtil.debug("UpdateChecker", "checkForUpdates", "更新检查时间到: " + currentTime);
            appDataManager.setLastUpdateCheckTime(currentTime);
            LogUtil.debug("UpdateChecker", "checkForUpdates", "检查时间已保存");
        }
        
        // 在后台线程中执行网络请求，避免阻塞UI线程
        new Thread(() -> {
            try {
                LogUtil.info("UpdateChecker", "checkForUpdates", "正在获取服务器版本信息...");
                VersionInfo versionInfo = getVersionInfoFromServer();
                LogUtil.info("UpdateChecker", "checkForUpdates", "从服务器获取到的版本信息: " + (versionInfo != null ? versionInfo.getLatest_version() : "null"));
                
                // 在EDT线程中更新UI
                SwingUtilities.invokeLater(() -> {
                    if (versionInfo != null && versionInfo.getLatest_version() != null && !versionInfo.getLatest_version().trim().isEmpty()) {
                        String latestVersion = versionInfo.getLatest_version().trim();
                        LogUtil.info("UpdateChecker", "checkForUpdates", "当前版本: " + CURRENT_VERSION + ", 服务器版本: " + latestVersion);
                        
                        // 检查当前版本是否在强制更新列表中
                        if (versionInfo.isMandatoryUpdate(CURRENT_VERSION)) {
                            // 强制更新
                            LogUtil.info("UpdateChecker", "checkForUpdates", "当前版本在强制更新列表中，必须更新到最新版本");
                            showMandatoryUpdateDialog(versionInfo);
                        } else {
                            // 检查是否设置了跳过此版本更新
                            if (appDataManager.isSkipVersionUpdate(latestVersion)) {
                                LogUtil.info("UpdateChecker", "checkForUpdates", "用户已选择跳过版本 " + latestVersion + " 的更新提示");
                                // 即使跳过提示，手动检查时也应给出反馈
                                if (isManualCheck) {
                                    JOptionPane.showMessageDialog(
                                        parentFrame,
                                        MessageFormat.format(languageManager.getString("dialog.update.message"), CURRENT_VERSION),
                                        languageManager.getString("dialog.update.title"),
                                        JOptionPane.INFORMATION_MESSAGE
                                    );
                                }
                                return;
                            }
                            
                            if (!CURRENT_VERSION.equals(latestVersion)) {
                                // 有新版本
                                LogUtil.info("UpdateChecker", "checkForUpdates", "发现新版本，显示更新对话框...");
                                showUpdateDialog(versionInfo);
                            } else {
                                // 已是最新版本
                                LogUtil.info("UpdateChecker", "checkForUpdates", "当前已是最新版本，无需更新");
                                // 手动检查更新时给出友好提示
                                if (isManualCheck) {
                                    JOptionPane.showMessageDialog(
                                        parentFrame,
                                        MessageFormat.format(languageManager.getString("dialog.update.message"), CURRENT_VERSION),
                                        languageManager.getString("dialog.update.title"),
                                        JOptionPane.INFORMATION_MESSAGE
                                    );
                                }
                            }
                        }
                    } else {
                        // 获取版本信息失败
                        LogUtil.error("UpdateChecker", "checkForUpdates", "检查更新失败：无法获取服务器版本信息");
                        JOptionPane.showMessageDialog(
                            parentFrame,
                            languageManager.getString("dialog.update.check.failed"),
                            languageManager.getString("dialog.update.title"),
                            JOptionPane.ERROR_MESSAGE
                        );
                    }
                });
            } catch (Exception e) {
                LogUtil.error("UpdateChecker", "checkForUpdates", "检查更新时发生异常: " + e.getMessage());
                e.printStackTrace();
                // 在EDT线程中显示错误信息
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(
                        parentFrame,
                        MessageFormat.format(languageManager.getString("dialog.update.check.error"), e.getMessage()),
                        languageManager.getString("dialog.update.title"),
                        JOptionPane.ERROR_MESSAGE
                    );
                });
            }
        }).start();
    }
    
    /**
     * 从服务器获取版本信息
     * @return 版本信息对象，如果获取失败返回null
     */
    private VersionInfo getVersionInfoFromServer() {
        try {
            LogUtil.info("UpdateChecker", "getVersionInfoFromServer", "连接到URL: " + VERSION_URL);
            String actualUrl = VERSION_URL;
            
            // 处理可能的重定向
            URL url = new URL(actualUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setInstanceFollowRedirects(false); // 手动处理重定向
            connection.setConnectTimeout(10000); // 10秒连接超时
            connection.setReadTimeout(10000);    // 10秒读取超时
            
            int responseCode = connection.getResponseCode();
            LogUtil.debug("UpdateChecker", "getVersionInfoFromServer", "服务器响应码: " + responseCode);
            
            // 手动处理重定向
            int redirectCount = 0;
            while ((responseCode == HttpURLConnection.HTTP_MOVED_TEMP || 
                    responseCode == HttpURLConnection.HTTP_MOVED_PERM ||
                    responseCode == HttpURLConnection.HTTP_SEE_OTHER) && 
                   redirectCount < 5) { // 最多重定向5次，防止无限循环
                redirectCount++;
                String redirectUrl = connection.getHeaderField("Location");
                LogUtil.debug("UpdateChecker", "getVersionInfoFromServer", "检测到重定向到: " + redirectUrl);
                
                if (redirectUrl != null) {
                    // 修复URL协议问题
                    if (redirectUrl.startsWith("//")) {
                        redirectUrl = "https:" + redirectUrl;
                    } else if (redirectUrl.startsWith("/")) {
                        // 相对路径，需要补全域名
                        redirectUrl = "https://kk22477350.jz.fkw.com" + redirectUrl;
                    } else if (!redirectUrl.startsWith("http://") && !redirectUrl.startsWith("https://")) {
                        // 其他情况，尝试补全为https
                        redirectUrl = "https://" + redirectUrl;
                    }
                    
                    LogUtil.debug("UpdateChecker", "getVersionInfoFromServer", "处理后的重定向URL: " + redirectUrl);
                    
                    // 使用重定向后的URL重新请求
                    connection.disconnect();
                    url = new URL(redirectUrl);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setInstanceFollowRedirects(false);
                    connection.setConnectTimeout(10000);
                    connection.setReadTimeout(10000);
                    responseCode = connection.getResponseCode();
                    LogUtil.debug("UpdateChecker", "getVersionInfoFromServer", "第" + redirectCount + "次重定向后服务器响应码: " + responseCode);
                } else {
                    break;
                }
            }
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder jsonResponse = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    jsonResponse.append(line);
                }
                reader.close();
                
                LogUtil.debug("UpdateChecker", "getVersionInfoFromServer", "读取到的JSON响应: " + jsonResponse.toString());
                
                // 解析JSON响应
                Gson gson = new Gson();
                VersionInfo versionInfo = gson.fromJson(jsonResponse.toString(), VersionInfo.class);
                LogUtil.debug("UpdateChecker", "getVersionInfoFromServer", "解析后的版本信息: " + versionInfo.getLatest_version());
                
                // 保存版本信息到本地文件
                saveVersionInfoToLocalFile(jsonResponse.toString());
                
                return versionInfo;
            } else {
                LogUtil.error("UpdateChecker", "getVersionInfoFromServer", "HTTP错误，响应码: " + responseCode);
                // 尝试读取错误响应内容
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
                    String line;
                    StringBuilder errorResponse = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        errorResponse.append(line).append("\n");
                    }
                    LogUtil.error("UpdateChecker", "getVersionInfoFromServer", "错误响应内容: " + errorResponse.toString());
                } catch (Exception e) {
                    LogUtil.error("UpdateChecker", "getVersionInfoFromServer", "读取错误响应内容失败: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            LogUtil.error("UpdateChecker", "getVersionInfoFromServer", "网络请求异常: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 保存版本信息到本地文件
     * @param jsonContent JSON内容
     */
    private void saveVersionInfoToLocalFile(String jsonContent) {
        try {
            // 获取本地保存的版本信息文件路径
            Path versionInfoFile = appDataManager.getAppDataDirectory().resolve("version_info.json");
            
            // 写入JSON内容到文件
            Files.write(versionInfoFile, jsonContent.getBytes());
            
            LogUtil.info("UpdateChecker", "saveVersionInfoToLocalFile", "版本信息已保存到本地文件: " + versionInfoFile.toString());
        } catch (Exception e) {
            LogUtil.error("UpdateChecker", "saveVersionInfoToLocalFile", "保存版本信息到本地文件时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 显示强制更新对话框
     * @param versionInfo 版本信息
     */
    private void showMandatoryUpdateDialog(VersionInfo versionInfo) {
        String latestVersion = versionInfo.getLatest_version();
        
        // 构建更新内容
        StringBuilder updateNotesBuilder = new StringBuilder();
        if (versionInfo.getUpdate_notes() != null && !versionInfo.getUpdate_notes().trim().isEmpty()) {
            // 将换行符替换为HTML的<br>标签
            String formattedNotes = versionInfo.getUpdate_notes().replace("\n", "<br>");
            updateNotesBuilder.append("<b>更新内容：</b><br>").append(formattedNotes).append("<br><br>");
        }
        
        String message = MessageFormat.format(
            languageManager.getString("dialog.mandatory.update.message"),
            latestVersion,
            CURRENT_VERSION,
            updateNotesBuilder.toString()
        );
        
        LogUtil.info("UpdateChecker", "showMandatoryUpdateDialog", "显示强制更新对话框，版本: " + latestVersion);
        
        Object[] options = {languageManager.getString("dialog.mandatory.update.button")};
        int choice = JOptionPane.showOptionDialog(
            parentFrame,
            message,
            languageManager.getString("dialog.mandatory.update.title"),
            JOptionPane.DEFAULT_OPTION,
            JOptionPane.WARNING_MESSAGE,
            null,
            options,
            options[0]
        );
        
        if (choice == 0) {
            // 用户点击了"立即更新"
            if (versionInfo.isDirectDownload()) {
                // 如果是直接下载，不立即退出程序，而是开始下载后再退出
                downloadAndUpdate(versionInfo, true); // 传递true表示这是强制更新
            } else {
                try {
                    // 打开默认浏览器访问更新页面
                    Desktop.getDesktop().browse(new URI(versionInfo.getDownload_url()));
                } catch (IOException | URISyntaxException ex) {
                    JOptionPane.showMessageDialog(
                        parentFrame,
                        MessageFormat.format(languageManager.getString("dialog.browser.error"), ex.getMessage()),
                        languageManager.getString("dialog.update.title"),
                        JOptionPane.ERROR_MESSAGE
                    );
                    ex.printStackTrace();
                }
                // 退出程序
                System.exit(0);
            }
        } else {
            // 用户关闭了对话框或点击了其他按钮，退出程序
            System.exit(0);
        }
    }

    /**
     * 显示更新对话框
     * @param versionInfo 版本信息
     */
    private void showUpdateDialog(VersionInfo versionInfo) {
        String latestVersion = versionInfo.getLatest_version();
        
        LogUtil.info("UpdateChecker", "showUpdateDialog", "显示更新对话框，版本: " + latestVersion);
        
        // 构建更新内容
        StringBuilder updateNotesBuilder = new StringBuilder();
        if (versionInfo.getUpdate_notes() != null && !versionInfo.getUpdate_notes().trim().isEmpty()) {
            // 将换行符替换为HTML的<br>标签
            String formattedNotes = versionInfo.getUpdate_notes().replace("\n", "<br>");
            updateNotesBuilder.append("<b>更新内容：</b><br>").append(formattedNotes).append("<br><br>");
        }
        
        String message = MessageFormat.format(
            languageManager.getString("dialog.update.available.message"),
            latestVersion,
            CURRENT_VERSION,
            updateNotesBuilder.toString()
        );
        
        // 创建自定义对话框以包含"不再询问"复选框
        JDialog dialog = new JDialog(parentFrame, languageManager.getString("dialog.update.available.title"), true);
        dialog.setLayout(new BorderLayout());
        
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 创建消息面板
        JPanel messagePanel = new JPanel(new BorderLayout());
        
        JLabel messageLabel = new JLabel(message);
        messageLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
        messagePanel.add(messageLabel, BorderLayout.CENTER);
        
        // 创建选项面板
        JPanel optionPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JCheckBox skipCheckBox = new JCheckBox(languageManager.getString("dialog.update.skip.version"));
        optionPanel.add(skipCheckBox);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton yesButton = new JButton(languageManager.getString("dialog.update.available.yes"));
        JButton noButton = new JButton(languageManager.getString("dialog.update.available.no"));
        
        buttonPanel.add(yesButton);
        buttonPanel.add(noButton);
        
        // 添加组件到主面板
        mainPanel.add(messagePanel, BorderLayout.NORTH);
        mainPanel.add(optionPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        dialog.add(mainPanel);
        
        // 设置按钮事件
        yesButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 如果用户选择跳过此版本，则保存设置
                if (skipCheckBox.isSelected()) {
                    appDataManager.setSkipVersionUpdate(latestVersion, true);
                }
                
                dialog.dispose();
                
                if (versionInfo.isDirectDownload()) {
                    // 直接下载更新
                    downloadAndUpdate(versionInfo, false); // 传递false表示这不是强制更新
                } else {
                    try {
                        // 打开默认浏览器访问更新页面
                        Desktop.getDesktop().browse(new URI(versionInfo.getDownload_url()));
                    } catch (IOException | URISyntaxException ex) {
                        JOptionPane.showMessageDialog(
                            parentFrame,
                            MessageFormat.format(languageManager.getString("dialog.browser.error"), ex.getMessage()),
                            languageManager.getString("dialog.update.title"),
                            JOptionPane.ERROR_MESSAGE
                        );
                        ex.printStackTrace();
                    }
                }
            }
        });
        
        noButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 如果用户选择跳过此版本，则保存设置
                if (skipCheckBox.isSelected()) {
                    appDataManager.setSkipVersionUpdate(latestVersion, true);
                }
                
                dialog.dispose();
            }
        });
        
        // 设置对话框属性
        dialog.pack();
        dialog.setResizable(false);
        dialog.setLocationRelativeTo(parentFrame);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        
        // 显示对话框
        dialog.setVisible(true);
    }
    
    /**
     * 下载并更新应用程序
     * @param versionInfo 版本信息
     * @param isMandatoryUpdate 是否为强制更新
     */
    private void downloadAndUpdate(VersionInfo versionInfo, boolean isMandatoryUpdate) {
        new Thread(() -> {
            try {
                // 获取下载URL
                String downloadUrl = versionInfo.getDownload_url();
                URL url = new URL(downloadUrl);
                
                // 创建连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(10000);
                connection.setReadTimeout(30000);
                
                // 检查响应码
                int responseCode = connection.getResponseCode();
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(
                            parentFrame,
                            MessageFormat.format(languageManager.getString("dialog.download.failed"), responseCode),
                            languageManager.getString("dialog.update.title"),
                            JOptionPane.ERROR_MESSAGE
                        );
                        // 如果是强制更新且下载失败，则退出程序
                        if (isMandatoryUpdate) {
                            System.exit(0);
                        }
                    });
                    return;
                }
                
                // 获取文件名
                String fileName = "BeatGeneratorInstaller.exe";
                String disposition = connection.getHeaderField("Content-Disposition");
                if (disposition != null && disposition.contains("filename=")) {
                    int index = disposition.indexOf("filename=");
                    if (index > 0) {
                        fileName = disposition.substring(index + 9);
                        // 移除可能的引号
                        if (fileName.startsWith("\"") && fileName.endsWith("\"")) {
                            fileName = fileName.substring(1, fileName.length() - 1);
                        }
                    }
                }
                
                // 获取应用程序数据目录
                Path downloadDir = appDataManager.getAppDataDirectory().resolve("updates");
                Files.createDirectories(downloadDir);
                Path downloadFile = downloadDir.resolve(fileName);
                
                // 显示下载进度对话框
                JDialog progressDialog = new JDialog(parentFrame, languageManager.getString("dialog.download.complete.title"), true);
                progressDialog.setLayout(new BorderLayout());
                
                JLabel statusLabel = new JLabel(MessageFormat.format(languageManager.getString("dialog.download.progress"), fileName));
                statusLabel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
                
                JProgressBar progressBar = new JProgressBar(0, 100);
                progressBar.setIndeterminate(false);
                progressBar.setStringPainted(true);
                
                JPanel panel = new JPanel(new BorderLayout());
                panel.add(statusLabel, BorderLayout.NORTH);
                panel.add(progressBar, BorderLayout.CENTER);
                panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
                
                progressDialog.add(panel);
                progressDialog.pack();
                progressDialog.setResizable(false);
                progressDialog.setLocationRelativeTo(parentFrame);
                
                // 在后台线程中显示进度对话框
                SwingUtilities.invokeLater(() -> {
                    progressDialog.setVisible(true);
                });
                
                // 开始下载
                long fileSize = connection.getContentLengthLong();
                try (InputStream inputStream = connection.getInputStream();
                     FileOutputStream outputStream = new FileOutputStream(downloadFile.toFile())) {
                    
                    byte[] buffer = new byte[4096];
                    long totalBytesRead = 0;
                    int bytesRead;
                    
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                        totalBytesRead += bytesRead;
                        
                        // 更新进度条
                        if (fileSize > 0) {
                            int progress = (int) ((totalBytesRead * 100) / fileSize);
                            final int finalProgress = progress;
                            SwingUtilities.invokeLater(() -> {
                                progressBar.setValue(finalProgress);
                                progressBar.setString(finalProgress + "%");
                            });
                        }
                    }
                }
                
                // 关闭进度对话框
                SwingUtilities.invokeLater(() -> {
                    progressDialog.dispose();
                });
                
                // 下载完成，询问是否立即安装
                int choice = JOptionPane.showConfirmDialog(
                    parentFrame,
                    MessageFormat.format(languageManager.getString("dialog.download.complete.message"), downloadFile.toString()),
                    languageManager.getString("dialog.download.complete.title"),
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE
                );
                
                if (choice == JOptionPane.YES_OPTION) {
                    // 使用桌面API打开安装文件
                    Desktop.getDesktop().open(downloadFile.toFile());
                }
                
                // 如果是强制更新，则在下载完成后退出程序
                if (isMandatoryUpdate) {
                    System.exit(0);
                }
            } catch (Exception ex) {
                LogUtil.error("UpdateChecker", "downloadAndUpdate", "下载更新时发生错误: " + ex.getMessage());
                ex.printStackTrace();
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(
                        parentFrame,
                        MessageFormat.format(languageManager.getString("dialog.download.error"), ex.getMessage()),
                        languageManager.getString("dialog.update.title"),
                        JOptionPane.ERROR_MESSAGE
                    );
                    // 如果是强制更新且下载失败，则退出程序
                    if (isMandatoryUpdate) {
                        System.exit(0);
                    }
                });
            }
        }).start();
    }
    
    /**
     * 下载并更新应用程序（原有方法，保持兼容性）
     * @param versionInfo 版本信息
     */
    private void downloadAndUpdate(VersionInfo versionInfo) {
        downloadAndUpdate(versionInfo, false);
    }
    
    /**
     * 检查本地保存的版本信息，判断当前版本是否在强制更新列表中
     */
    private void checkLocalMandatoryUpdate() {
        try {
            // 获取本地保存的版本信息文件路径
            Path versionInfoFile = appDataManager.getAppDataDirectory().resolve("version_info.json");
            
            // 检查文件是否存在
            if (Files.exists(versionInfoFile)) {
                // 读取本地保存的版本信息
                String jsonContent = new String(Files.readAllBytes(versionInfoFile));
                Gson gson = new Gson();
                VersionInfo localVersionInfo = gson.fromJson(jsonContent, VersionInfo.class);
                
                // 检查当前版本是否在强制更新列表中
                if (localVersionInfo != null && localVersionInfo.isMandatoryUpdate(CURRENT_VERSION)) {
                    // 当前版本在强制更新列表中，将上次更新时间设为0，确保下次会检查更新
                    LogUtil.info("UpdateChecker", "checkLocalMandatoryUpdate", "当前版本在本地保存的强制更新列表中，重置上次检查时间");
                    appDataManager.setLastUpdateCheckTime(0);
                }
            }
        } catch (Exception e) {
            LogUtil.error("UpdateChecker", "checkLocalMandatoryUpdate", "检查本地版本信息时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
}